<?php
/**
 * wmfl.cn version 5.0
 * -----------------------------------------------
 * @author sy <409014125@qq.com>
 * @link http://www.utuo88.com
 * @copyright 2014 Utuo Tech co.,Ltd
 */
namespace Partner\Model;
use Think\Model;

/**
 * 管理员行为模型
 * @author huajie <banhuajie@163.com>
 */
class DynaFormModel extends Model {
	
	protected $_auto = array(
			array('config', 'getConfig', self::MODEL_BOTH, 'callback'),
	);
	
	/**
	 * 获得颜色配置信息 格式: 变量名|标题[|类型(string,number,color,image,select)[|数据源]]#attrs:placeholder=信息&other=错误信息
	 * @return string
	 */
	public function getConfig() {
		$result = array();
		$config = I("config");
		foreach(explode("\n", $config) as $v) {
			$arr = array();
			list($v, $attrs) = explode('#attrs:', $v);
			list($varName, $varTitle, $varType, $varDataSource) = explode('|', trim($v));
			$varName and $varTitle and $varType and $arr = array('varName'=>$varName, 'varTitle' => $varTitle, 'varType' => $varType);
			if($varDataSource) {
				$dataSource = array();
				foreach (explode(',', $varDataSource) as $attr_string) {
					list($attr_key, $attr_value) = explode('=', $attr_string);
					$dataSource[$attr_key] = $attr_value;
				}
				$arr['varDataSource'] = $dataSource;
			}
			if( !empty($attrs) ) {
				$arr['attrs'] = array();
				foreach (explode('&', $attrs) as $v) {
					list($varName, $varValue) = explode('=', $v);
					!empty($varName) and $arr['attrs'][$varName] = $varValue;
				}
			}
			empty($arr) or $result[] = $arr;
		}
		return serialize($result);
	}
	
	
	/**
	 * 转为配置字符串格式显示
	 * @param unknown $data 
	 */
	public function parseArray($array) {
		$result = array();
		foreach ($array as $k => $v) {
			$arr = array();
			$arr[] = $v['varName'];
			$arr[] = $v['varTitle'];
			$arr[] = $v['varType'];
			if (!empty($v['varDataSource'])){
				$data = array();
				foreach ($v['varDataSource'] as $attr => $value){
					$data[] = sprintf('%s=%s',$attr,$value);
				}
				$arr[] = join(',', $data);
			}
			$str = join('|', $arr);
			if( !empty($v['attrs']) ) {
				$attrs = array();
				foreach ( $v['attrs'] as $k => $v) {
					!empty($k) and $attrs[] = $k."=".$v;
				}
				!empty($attrs) and $str.="#attrs:".join("&", $attrs);
			}
			$result[] = $str;
		}
		return join("\n", $result);
	}
}
